package com.demotest.service.util;

import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.awt.image.ImageObserver;
import java.awt.image.MemoryImageSource;
import java.awt.image.PixelGrabber;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.Character;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.imageio.ImageIO;

import com.rongzer.pos.util.StringUtil;
import org.apache.commons.collections4.MapUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sun.misc.BASE64Decoder;

public class FontImageUtil {
    private static final Logger log = LoggerFactory.getLogger(FontImageUtil.class);

    public static void createImage(Map<String, Object> stringMap, Font font, File outFile, Integer width, Integer height) throws Exception {
        BufferedImage image = new BufferedImage(width, height, 4);
        Graphics g = image.getGraphics();
        g.setClip(0, 0, width, height);
        g.setColor(Color.white);
        g.fillRect(0, 0, width, height);
        g.setColor(Color.black);
        log.info("realserverfilepath:");
        File file = new File("resource/images/bailian-logo.png");
        int top = 2;
        if (file.exists()) {
            g.drawImage(ImageIO.read(new File("resource/images/bailian-logo.png")), 100, 20, 200, 50, new ImageObserver() {
                @Override
                public boolean imageUpdate(Image img, int infoflags, int x, int y, int width2, int height2) {
                    return true;
                }
            });
            top = 3;
        }
        if (!MapUtils.isEmpty(stringMap)) {
            for (int i = 1; i <= stringMap.size(); i++) {
                int x = 5;
                String center = StringUtil.toStringWithEmpty(stringMap.get(i + "_CENTER"));
                int fontSize = 12;
                int fontType = 0;
                if (!StringUtil.toStringWithEmpty(stringMap.get(i + "_FONTSIZE")).isEmpty()) {
                    fontSize = Integer.parseInt(StringUtil.toStringWithEmpty(stringMap.get(i + "_FONTSIZE")));
                }
                if (!StringUtil.toStringWithEmpty(stringMap.get(i + "_FONTTYPE")).isEmpty()) {
                    fontType = Integer.parseInt(StringUtil.toStringWithEmpty(stringMap.get(i + "_FONTTYPE")));
                }
                Font fontTemp = new Font("微软雅黑", fontType, fontSize);
                FontMetrics fm = g.getFontMetrics(fontTemp);
                if (!center.isEmpty()) {
                    int stringWidth = fm.stringWidth(StringUtil.toStringWithEmpty(stringMap.get(i + "")));
                    x = (width.intValue() / 2) - (stringWidth / 2);
                }
                g.setFont(fontTemp);
                if (StringUtil.toStringWithEmpty(stringMap.get(i + "")).isEmpty()) {
                    String strFirst = StringUtil.toStringWithEmpty(stringMap.get(i + "_1"));
                    String strSecond = StringUtil.toStringWithEmpty(stringMap.get(i + "_2"));
                    String strThird = StringUtil.toStringWithEmpty(stringMap.get(i + "_3"));
                    String strFourth = StringUtil.toStringWithEmpty(stringMap.get(i + "_4"));
                    g.drawString(strFirst, x, 20 * (i + top));
                    g.drawString(strSecond, x + ((width.intValue() * 140) / 400), 20 * (i + top));
                    g.drawString(strThird, x + ((width.intValue() * 260) / 400), 20 * (i + top));
                    g.drawString(strFourth, x + ((width.intValue() * 320) / 400), 20 * (i + top));
                } else {
                    g.drawString(StringUtil.toStringWithEmpty(stringMap.get(i + "")), x, 20 * (i + top));
                }
            }
        }
        g.dispose();
        ImageIO.write(image, "png", outFile);
    }

    public static boolean generateImage(String base64ImgStr, String filePath) {
        if (base64ImgStr == null) {
            return false;
        }
        BASE64Decoder decoder = new BASE64Decoder();
        OutputStream out = null;
        try {
            byte[] bytes = decoder.decodeBuffer(base64ImgStr);
            for (int i = 0; i < bytes.length; i++) {
                if (bytes[i] < 0) {
                    int i2 = i;
                    bytes[i2] = (byte) (bytes[i2] + 256);
                }
            }
            out = new FileOutputStream(filePath);
            out.write(bytes);
            out.flush();
            if (null != out) {
                try {
                    out.close();
                } catch (IOException e) {
                }
            }
            return true;
        } catch (Exception e2) {
            if (null != out) {
                try {
                    out.close();
                } catch (IOException e3) {
                }
            }
            return false;
        } catch (Throwable th) {
            if (null != out) {
                try {
                    out.close();
                } catch (IOException e4) {
                }
            }
            throw th;
        }
    }

    public static void createImageByXY(Map<String, Object> stringMap, Font font, File outFile, Integer width, Integer canvasHeight) throws Exception {
        int maxHeight;
        BufferedImage image = new BufferedImage(width.intValue(), canvasHeight.intValue(), 1);
        Graphics g = image.getGraphics();
        g.setClip(0, 0, width.intValue(), canvasHeight.intValue());
        g.fillRect(0, 0, width.intValue(), canvasHeight.intValue());
        g.setColor(Color.black);
        if (!StringUtil.toStringWithEmpty(stringMap.get("image")).isEmpty()) {
            String filePath = StringUtil.toStringWithEmpty(stringMap.get("image"));
            int imageX = Integer.parseInt(StringUtil.toStringWithEmpty(stringMap.get("image_X")));
            int imageY = Integer.parseInt(StringUtil.toStringWithEmpty(stringMap.get("image_Y")));
            int imageWidth = Integer.parseInt(StringUtil.toStringWithEmpty(stringMap.get("image_WIDTH")));
            int imageHeight = Integer.parseInt(StringUtil.toStringWithEmpty(stringMap.get("image_HEIGHT")));
            FileInputStream imageFileInputStream = new FileInputStream(filePath);
            g.drawImage(ImageIO.read(imageFileInputStream), imageX, imageY, imageWidth, imageHeight, new ImageObserver() { // from class: com.rongzer.pos.util.FontImageUtil.2
                @Override
                public boolean imageUpdate(Image img, int infoflags, int x, int y, int width2, int height) {
                    return false;
                }
            });
            imageFileInputStream.close();
        }
        if (!MapUtils.isEmpty(stringMap)) {
            for (int i = 1; i <= stringMap.size(); i++) {
                String center = StringUtil.toStringWithEmpty(stringMap.get(i + "_CENTER"));
                int fontSize = 12;
                int fontType = 0;
                int x = 5;
                int y = 0;
                if (!StringUtil.toStringWithEmpty(stringMap.get(i + "_FONTSIZE")).isEmpty()) {
                    fontSize = Integer.parseInt(StringUtil.toStringWithEmpty(stringMap.get(i + "_FONTSIZE")));
                }
                if (!StringUtil.toStringWithEmpty(stringMap.get(i + "_FONTTYPE")).isEmpty()) {
                    fontType = Integer.parseInt(StringUtil.toStringWithEmpty(stringMap.get(i + "_FONTTYPE")));
                }
                Font fontTemp = new Font(font.getFontName(), fontType, fontSize);
                FontMetrics fm = g.getFontMetrics(fontTemp);
                g.setFont(fontTemp);
                if (!StringUtil.toStringWithEmpty(stringMap.get(i + "_X")).isEmpty()) {
                    x = Integer.parseInt(StringUtil.toStringWithEmpty(stringMap.get(i + "_X")));
                }
                if (!center.isEmpty()) {
                    int stringWidth = fm.stringWidth(StringUtil.toStringWithEmpty(stringMap.get(i + "")));
                    x = (width.intValue() / 2) - (stringWidth / 2);
                }
                if (!StringUtil.toStringWithEmpty(stringMap.get(i + "_Y")).isEmpty()) {
                    y = Integer.parseInt(StringUtil.toStringWithEmpty(stringMap.get(i + "_Y")));
                }
                if (!StringUtil.toStringWithEmpty(stringMap.get(i + "_X_X")).isEmpty()) {
                    int x2 = fm.stringWidth(StringUtil.toStringWithEmpty(stringMap.get(i + "")));
                    x = Integer.parseInt(StringUtil.toStringWithEmpty(stringMap.get(i + "_X_X"))) - x2;
                }
                g.drawString(StringUtil.toStringWithEmpty(stringMap.get(i + "")), x, y);
            }
        }
        g.dispose();
        int maxHeight2 = 0;
        for (int j = 0; j < image.getHeight(); j++) {
            for (int i2 = 0; i2 < image.getWidth(); i2++) {
                int rgbData = image.getRGB(i2, j);
                if (rgbData != -1) {
                    maxHeight2 = j;
                }
            }
        }
        if (width.intValue() % 2 != 0) {
            width = Integer.valueOf(width.intValue() - 1);
        }
        if (maxHeight2 % 2 != 0) {
            maxHeight = maxHeight2 + 5;
        } else {
            maxHeight = maxHeight2 + 4;
        }
        BufferedImage subImage = image.getSubimage(0, 0, width.intValue(), maxHeight);
        ImageIO.write(subImage, "png", outFile);
    }

    public static boolean deleteFile(String fileName) {
        File file = new File(fileName);
        if (file.exists() && file.isFile()) {
            if (file.delete()) {
                System.out.println("删除单个文件" + fileName + "成功！");
                return true;
            }
            System.out.println("删除单个文件" + fileName + "失败！");
            return false;
        }
        System.out.println("删除单个文件失败：" + fileName + "不存在！");
        return false;
    }

    public static byte[] changeByte(int data) {
        byte b4 = (byte) (data >> 24);
        byte b3 = (byte) ((data << 8) >> 24);
        byte b2 = (byte) ((data << 16) >> 24);
        byte b1 = (byte) ((data << 24) >> 24);
        byte[] bytes = {b1, b2, b3, b4};
        return bytes;
    }

    public static void convertImageToBmp(String fromFilePath, String targetPath) throws IOException {
        BufferedImage sourceImg = ImageIO.read(new File(fromFilePath));
        int h = sourceImg.getHeight();
        int w = sourceImg.getWidth();
        int[] pixels = new int[w * h];
        PixelGrabber pg = new PixelGrabber(sourceImg, 0, 0, w, h, pixels, 0, w);
        try {
            pg.grabPixels();
        } catch (Exception e) {
            log.error("处理被异常中断！请重试！", e);
        }
        for (int j = 0; j < h; j++) {
            for (int i = 0; i < w; i++) {
                int gray = ((int) (((pixels[(w * j) + i] >> 16) & 255) * 0.8d)) + ((int) (((pixels[(w * j) + i] >> 8) & 255) * 0.1d)) + ((int) ((pixels[(w * j) + i] & 255) * 0.1d));
                pixels[(w * j) + i] = (-16777216) | (gray << 16) | (gray << 8) | gray;
            }
        }
        MemoryImageSource s = new MemoryImageSource(w, h, pixels, 0, w);
        Image img = Toolkit.getDefaultToolkit().createImage(s);
        BufferedImage buf = new BufferedImage(w, h, 12);
        buf.createGraphics().drawImage(img, 0, 0, (ImageObserver) null);
        ImageIO.write(buf, "BMP", new File(targetPath));
    }

    public static List<String> breakString(String targetString, int breakLength) {
        List<String> resultList = new ArrayList<>();
        double printLength = 0.0d;
        StringBuffer buffer = new StringBuffer();
        int i = 0;
        while (true) {
            if (i >= targetString.length()) {
                break;
            }
            int cp = targetString.codePointAt(i);
            if (!Character.isSupplementaryCodePoint(cp)) {
                char c = (char) cp;
                if (isChinese(c)) {
                    printLength += 1.5d;
                } else if ('.' != c) {
                    printLength += 1.0d;
                }
                buffer.append(c);
                if (i == targetString.length() - 1) {
                    resultList.add(buffer.toString());
                    break;
                } else if (printLength > breakLength) {
                    resultList.add(buffer.toString());
                    buffer.delete(0, buffer.length());
                    printLength = 0.0d;
                }
            }
            i++;
        }
        return resultList;
    }

    public static boolean isChinese(char c) {
        Character.UnicodeBlock ub = Character.UnicodeBlock.of(c);
        if (ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS || ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A || ub == Character.UnicodeBlock.GENERAL_PUNCTUATION || ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION || ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS) {
            return true;
        }
        return false;
    }
}
